/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ejb;

import com.entidades.Cliente;
import com.entidades.Transacao;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Ricardo
 */
@Stateless
public class TransacaoBean implements TransacaoRemote {


    @PersistenceContext
    private EntityManager em;

    public void registraTransacao(Transacao t, Cliente c){
        adicionaCredito(t,c);
        t.setDataHora(new Date());
        em.persist(t);
        em.flush();

    }

    private void adicionaCredito(Transacao t, Cliente c) {
        int novoSaldo = c.getSaldoSms() + t.getQuantidade();
        c.setSaldoSms(novoSaldo);
        t.setDataHora(new Date());
        em.merge(c);
        em.flush();
    }

     public List<Transacao> findByCliente(Cliente c) {
        Query query = em.createQuery("Select t from Transacao t where t.usuario.cliente =:c")
                                     .setParameter("c", c);
        return query.getResultList();
    }
 
}
